package com.example.demo.controller;

import com.example.demo.common.AppResult;
import com.example.demo.common.ResultCode;
import com.example.demo.config.AppConfig;
import com.example.demo.model.Article;
import com.example.demo.model.User;
import com.example.demo.services.IArticleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author baekhyun
 **/
@Api(tags = "帖子接口")
@RestController
@RequestMapping("/article")
@Slf4j
public class ArticleController {

    @Resource
    private IArticleService articleService;

    /**
     * 获取帖子列表
     * @param boardId
     * @return
     */
    @ApiOperation("获取帖子列表")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(@ApiParam("版块Id") @RequestParam(value = "boardId",required = false) Long boardId){
        //定义要返回的结果
        List<Article> results;
        if (boardId==null){
            //1、boardId为空时，获取所有帖子
            results=articleService.selectAll();
        }else {
            //2、boardId不为空时，获取所有帖子
            results=articleService.selectByBoardId(boardId);
        }
        //防止返回的结果是null
        if (results==null){
            results=new ArrayList<>();
        }
        //返回结果
        return AppResult.success(results);
    }

    /**
     * 发布帖子
     * @param request
     * @param boardId
     * @param title
     * @param content
     * @return
     */
    @ApiOperation("发布帖子")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @ApiParam("版块Id") @RequestParam("boardId") @NonNull Long boardId,
                            @ApiParam("标题") @RequestParam("title") @NonNull String title,
                            @ApiParam("内容") @RequestParam("content") @NonNull String content){
        //获取当前登录用户
        HttpSession session= request.getSession(false);
        User user=(User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        //判断用户状态
        if (user.getState()==1){
            //返回错误描述
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //构造帖子对象
        Article article=new Article();
        article.setUserId(user.getId());
        article.setBoardId(boardId);
        article.setTitle(title);
        article.setContent(content);
        //调用service
        articleService.create(article);
        //返回结果
        return AppResult.success("发布成功");
    }

    @ApiOperation("获取帖子详情")
    @GetMapping("/details")
    public AppResult<Article> getDetails(HttpServletRequest request,
                                         @ApiParam("帖子Id") @RequestParam("id") @NonNull Long id){
        //获取当前登录用户
        HttpSession session= request.getSession(false);
        User user=(User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        //调用service
        Article article=articleService.selectDetailById(id);
        //判断当前登录用户是否为帖子作者
        if (user.getId()==article.getUserId()){
            //设置所有者标识为true
            article.setOwn(true);
        }
        //返回结果
        return AppResult.success(article);
    }

    @ApiOperation("更新帖子")
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request,
                            @ApiParam("帖子id") @RequestParam("id") @NonNull Long id,
                            @ApiParam("帖子标题") @RequestParam("title") @NonNull String title,
                            @ApiParam("帖子正文") @RequestParam("content") @NonNull String content){
        //1、校验用户状态，禁言状态不能更新帖子
        HttpSession session= request.getSession(false);
        User user=(User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        if (user.getState()==1){
            //返回错误描述
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //2、查询帖子详情
        Article article=articleService.selectDetailById(id);
        //3、校验帖子状态(是否删除，是否封贴)
        if (article==null || article.getDeleteState()==1){
            //帖子不存在或已删除返回错误描述
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //4、校验当前登录用户是不是帖子的作者
        if (user.getId() != article.getUserId()){
            //返回错误描述
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        //调用service
        articleService.modify(id,title,content);
        //返回结果
        return AppResult.success();
    }

    @ApiOperation(("删除帖子"))
    @GetMapping("/delete")
    public AppResult deleteById(HttpServletRequest request,
                                @ApiParam("帖子Id") @RequestParam("id") @NonNull Long id){
        //1、用户是否禁言
        HttpSession session= request.getSession(false);
        User user=(User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        if (user.getState()==1){
            //返回错误描述
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //查询帖子信息
        Article article=articleService.selectDetailById(id);
        //2、帖子是否存在或已经删除
        if (article==null || article.getDeleteState()==1){
            //返回错误描述
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //3、用户是否是作者
        if (article.getUserId()!= user.getId()){
            //返回错误描述
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //调用service执行删除
        articleService.deleteById(id);
        //返回成功
        return AppResult.success();
    }

    /**
     * 根据用户Id查询帖子列表
     * @param userId
     * @return
     */
    @ApiOperation("根据用户Id查询帖子列表")
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId(@ApiParam("用户Id") @RequestParam(value = "userId") @NonNull Long userId){
        //查询用户的帖子列表
        List<Article> result=articleService.selectByUserId(userId);
        log.info("查询用户帖子列表，userId="+userId);
        //返回列表
        return AppResult.success(result);
    }
}
